package com.sdhs.paas.gateway.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.sdhs.paas.gateway.config.AcmanageConfig;
import com.sdhs.paas.gateway.model.AmePolicy;


public class PaasAccessUtil
{
//	@Autowired
//	private static AcmanageConfig acmanageConfig;
	public static boolean hasPolicy(String userId){
		//根据userId查询出当前用户所具有的所有资源信息
		List<AmePolicy> amePolicyList = getPolicy(userId);
		boolean flag = amePolicyList.contains("/jwt/token");
		return true;
	}
	
	private static  List<AmePolicy> getPolicy(String userId){
		List<AmePolicy> resourceList = new ArrayList<AmePolicy>();
		Map<String, List<AmePolicy>> policy = getAllPolicyFromRemote(userId);
		resourceList = policy.get(userId);
		return resourceList;
	}
	
	private static Map<String, List<AmePolicy>> getAllPolicyFromRemote(final String userId){
		Map<String, List<AmePolicy>> policiesCache = (Map)AmeCacheUtil.get(AmeCacheUtil.POLICY_CACHE_NAME, userId, AmeCacheUtil.POLICY_CACHE_EXPIRY);
	    if (policiesCache != null) {
	      return policiesCache;
	    }
	    final AcmanageConfig acmanageConfig = (AcmanageConfig)SpringContextUtil.getBean(AcmanageConfig.class);
	    //通过请求用户中心，根据userId获取用户所具有的用户资源，并通过缓存缓存一下。
	    Map<String, List<AmePolicy>> resources = new HashMap<String, List<AmePolicy>>();
	    List<AmePolicy> resourceList = new ArrayList<AmePolicy>();
	    //从用户权限中心根据userId获取权限信息，此处是模拟数据
//	    resourceList = setResourceList("",userId);
	    String policyUrl = acmanageConfig.getOpenUrls().getPolicy();
	    Object obj = RestTemplateUtil.get(policyUrl, userId);
	    if(obj == null){
	    	return resources;
	    }
	    Map<String,Object> resourcemap = (Map<String, Object>) obj;
	    resourceList = setResourceList(resourcemap);
	    List<AmePolicy> amePolicyList = null;
	    for (AmePolicy amePolicy : resourceList) {
	    	amePolicyList = new ArrayList<AmePolicy>();
	    	if(resources.containsKey(amePolicy.getResource())){
	    		amePolicyList = resources.get(amePolicy.getResource());
	    		amePolicyList.add(amePolicy);
		    	resources.put(amePolicy.getResource(), amePolicyList);
	    	}
	    	amePolicyList.add(amePolicy);
	    	resources.put(amePolicy.getResource(), amePolicyList);
		}
	    AmeCacheUtil.put(AmeCacheUtil.POLICY_CACHE_NAME, userId, resources);
	    return resources;
	}
	
//  private static Map<String, List<AmePolicy>> getAllPolicyFromRemote(final String accountName)
//  {
//    Map policiesCache = (Map)AmeCacheUtil.get(AmeCacheUtil.POLICY_CACHE_NAME, accountName, AmeCacheUtil.POLICY_CACHE_EXPIRY);
//    if (policiesCache != null) {
//      return policiesCache;
//    }
//
//    final AcmanageConfig acmanageConfig = (AcmanageConfig)SpringContextUtil.getBean(AcmanageConfig.class);
//    String policyUrl = acmanageConfig.getOpenUrls().getPolicy();
//
//    Object object = RestTemplateUtil.get(policyUrl, new HashMap(10)
//    {
//    }
//    , new HashMap(10)
//    {
//    });
//    Map policies = new HashMap();
//    if ((object instanceof JSONArray)) {
//      JSONArray array = (JSONArray)object;
//      for (int i = 0; i < array.size(); i++) {
//        String policyDataStr = array.getJSONObject(i).getString("policyData");
//        json2Policies(JSON.parse(policyDataStr), policies);
//      }
//    }
//
//    AmeCacheUtil.put(AmeCacheUtil.POLICY_CACHE_NAME, accountName, policies);
//    return policies;
//  }
//
//  private static void json2Policies(Object object, Map<String, List<AmePolicy>> policies)
//  {
//    if ((object instanceof JSONArray)) {
//      JSONArray array = (JSONArray)object;
//      for (int i = 0; i < array.size(); i++)
//        json2Policies(array.get(i), policies);
//    }
//    else if ((object instanceof JSONObject)) {
//      JSONObject jsonObject = (JSONObject)object;
//      String resource = jsonObject.getString("resource");
//      List actions = getStringArrayFromObject(jsonObject.get("action"));
//
//      AmePolicyAttr policyAttr = new AmePolicyAttr();
//      policyAttr.setAttr(new HashMap());
//      if ((jsonObject.get("attrs") instanceof JSONObject)) {
//        JSONObject jsonAttrs = jsonObject.getJSONObject("attrs");
//        if (jsonAttrs != null) {
//          Map attr = new HashMap();
//          for (Map.Entry entry : jsonAttrs.entrySet()) {
//            if (((String)entry.getKey()).equals("ownerId"))
//              policyAttr.setOwnerId(Long.valueOf(Long.parseLong((String)entry.getValue())));
//            else if ((((String)entry.getKey()).equals("ownerName")) || (((String)entry.getKey()).equals("owner")))
//              policyAttr.setOwnerName((String)entry.getValue());
//            else {
//              attr.put(entry.getKey(), getStringSetFromObject(entry.getValue()));
//            }
//          }
//          policyAttr.setAttr(attr);
//        }
//      }
//
//      AmePolicy amePolicy = new AmePolicy();
//      amePolicy.setResource(resource);
//      amePolicy.setActions(actions);
//      amePolicy.setPolicyAttr(policyAttr);
//
//      List amePolicyList = new ArrayList();
//      if (policies.containsKey(resource)) {
//        amePolicyList = (List)policies.get(resource);
//      }
//      amePolicyList.add(amePolicy);
//      policies.put(resource, amePolicyList);
//    }
//  }
//
  private static List<String> str2List(String str)
  {
    return new ArrayList()
    {
    	{add(str);}
    };
  }

  public static boolean contains(List<String> policyConfig, String value)
  {
    if ((policyConfig != null) && ((policyConfig.contains("*")) || (policyConfig.contains(value)))) {
      return true;
    }
    return false;
  }
//
//  private static Set<String> getStringSetFromObject(Object object)
//  {
//    Set valueList = new HashSet();
//    if ((object instanceof JSONArray)) {
//      JSONArray array = (JSONArray)object;
//      for (int i = 0; i < array.size(); i++) {
//        if (array.get(i) != null)
//          valueList.add(array.get(i).toString());
//      }
//    }
//    else if ((object != null) && (((object instanceof JSONObject)) || ((object instanceof String))) && 
//      (!StringUtils.isEmpty(object.toString()))) {
//      valueList.add(object.toString());
//    }
//
//    return valueList;
//  }
//
//  private static List<String> getStringArrayFromObject(Object object)
//  {
//    List valueList = new ArrayList();
//    if ((object instanceof JSONArray)) {
//      JSONArray array = (JSONArray)object;
//      for (int i = 0; i < array.size(); i++) {
//        if (array.get(i) != null)
//          valueList.add(array.get(i).toString());
//      }
//    }
//    else if ((object != null) && (((object instanceof JSONObject)) || ((object instanceof String)))) {
//      valueList.add(object.toString());
//    }
//    return valueList;
//  }
//
//  private static List<Long> getLongArrayFromObject(Object object)
//  {
//    List valueList = new ArrayList();
//    if ((object instanceof JSONArray)) {
//      JSONArray array = (JSONArray)object;
//      for (int i = 0; i < array.size(); i++) {
//        if (array.get(i) != null)
//          valueList.add(array.getLong(i));
//      }
//    }
//    else if ((object != null) && (((object instanceof JSONObject)) || ((object instanceof String)))) {
//      valueList.add(Long.valueOf(Long.parseLong(object.toString())));
//    }
//    return valueList;
//  }
//
//  public static Map<String, List<AmePolicy>> getAllPolicy(String accountName)
//  {
//    Map policyMap = getAllPolicyFromRemote(accountName);
//    return policyMap;
//  }
//
  public static List<AmePolicy> getPolicy(String accountName, String reourceName)
  {
    Map policyMap = getAllPolicyFromRemote(accountName);
    return (List)policyMap.get(reourceName);
  }
//
//  public static List<AmePolicyAttr> getPolicyAttrs(String accountName, String reourceName, String actionName)
//  {
//    List<AmePolicy> amePolicyList = getPolicy(accountName, reourceName);
//    List attrs = new ArrayList();
//    boolean hasAllOwnerAttr = false;
//    for (AmePolicy amePolicy : amePolicyList) {
//      if (contains(amePolicy.getActions(), actionName)) {
//        if (amePolicy.getPolicyAttr() != null) {
//          attrs.add(amePolicy.getPolicyAttr());
//        } else if (!hasAllOwnerAttr) {
//          AmePolicyAttr attr = new AmePolicyAttr();
//          attr.setAttr(new HashMap());
//          attrs.add(attr);
//          hasAllOwnerAttr = true;
//        }
//      }
//    }
//    return attrs;
//  }
//
  public static boolean hasPolicy(String accountName, AmePolicy queryPolicy)
  {
    List amePolicyList = getPolicy(accountName, queryPolicy.getResource());

    if (amePolicyList == null) {
      return false;
    }
    boolean hasAccessAuth = false;
    AmePolicy amePolicy = null;
    for (Iterator localIterator1 = amePolicyList.iterator(); localIterator1.hasNext(); ) { 
    	amePolicy = (AmePolicy)localIterator1.next();
      for (String action : queryPolicy.getActions())
        if (contains(amePolicy.getActions(), action))
          hasAccessAuth = true;
    }
    if ((queryPolicy.getPolicyAttr() == null) && (hasAccessAuth)) {
      return true;
    }
    return false;
  }

  public static boolean hasPolicy(String accountName, List<AmePolicy> policies)
  {
    for (AmePolicy policy : policies) {
//      if (!hasPolicy(accountName, policy)) {
//        return false;
//      }
    }
    return true;
  }

  public static boolean hasPolicy(String accountName, String reourceName, String actionName)
  {
    AmePolicy policy = new AmePolicy();
    policy.setResource(reourceName);
    policy.setActions(str2List(actionName));
    return hasPolicy(accountName, policy);
  }
  private static List<AmePolicy> setResourceList(Map<String,Object> map){
	  List<Map<String,Object>> rList = (List<Map<String, Object>>) map.get("policyData");
	  List<AmePolicy> resourceList = new ArrayList<AmePolicy>();
	  List<String> actionList = null;
	  for(Map<String,Object> obj : rList){
		  actionList = new ArrayList<String>();
		  actionList.add(String.valueOf(obj.get("actions")));
		  AmePolicy amePolicy = new AmePolicy();
		  amePolicy.setResource(String.valueOf(obj.get("resource")));
		  amePolicy.setActions(actionList);
		  resourceList.add(amePolicy);
	  }
	  return resourceList;
  }
  private static List<AmePolicy> setResourceList(String uri,String userId){
		List<AmePolicy> resourceList = new ArrayList<AmePolicy>();
		AmePolicy amePolicy = new AmePolicy();
		List<String> actions = new ArrayList<String>(){{add("list");}};
		amePolicy.setResource("log");
		amePolicy.setActions(actions);
		resourceList.add(amePolicy);
		amePolicy = new AmePolicy();
		amePolicy.setResource("encache");
		amePolicy.setActions(actions);
		resourceList.add(amePolicy);
		amePolicy = new AmePolicy();
		amePolicy.setResource("amqp");
		amePolicy.setActions(actions);
		resourceList.add(amePolicy);
		amePolicy = new AmePolicy();
		amePolicy.setResource("mail");
		amePolicy.setActions(actions);
		resourceList.add(amePolicy);
		amePolicy = new AmePolicy();
		amePolicy.setResource("flow");
		amePolicy.setActions(actions);
		resourceList.add(amePolicy);
		amePolicy = new AmePolicy();
		amePolicy.setResource("jwt");
		amePolicy.setActions(actions);
		resourceList.add(amePolicy);
		amePolicy = new AmePolicy();
		amePolicy.setResource("job");
		amePolicy.setActions(actions);
		resourceList.add(amePolicy);
		amePolicy = new AmePolicy();
		amePolicy.setResource("app");
		amePolicy.setActions(actions);
		resourceList.add(amePolicy);
		amePolicy = new AmePolicy();
		amePolicy.setResource("loginhistory");
		amePolicy.setActions(actions);
		resourceList.add(amePolicy);
		amePolicy = new AmePolicy();
		amePolicy.setResource("menu");
		amePolicy.setActions(actions);
		resourceList.add(amePolicy);
		amePolicy = new AmePolicy();
		amePolicy.setResource("organ");
		amePolicy.setActions(actions);
		resourceList.add(amePolicy);
		amePolicy = new AmePolicy();
		amePolicy.setResource("resource");
		amePolicy.setActions(actions);
		resourceList.add(amePolicy);
		amePolicy = new AmePolicy();
		amePolicy.setResource("role");
		amePolicy.setActions(actions);
		resourceList.add(amePolicy);
		amePolicy = new AmePolicy();
		amePolicy.setResource("roleResource");
		amePolicy.setActions(actions);
		resourceList.add(amePolicy);
//		amePolicy = new AmePolicy();
//		amePolicy.setResource("serve");
//		amePolicy.setActions(actions);
//		resourceList.add(amePolicy);
		amePolicy = new AmePolicy();
		amePolicy.setResource("user");
		amePolicy.setActions(actions);
		resourceList.add(amePolicy);
		return resourceList;
	}
}